<?php

namespace services\infusion;

use common\models\base\Drug;
use common\models\base\DrugConfig;
use common\models\patient\InfusionQueueDrug;
use services\base\DrugService;
use common\components\Service;
use Yii;

/**
 * Class QueueDrugService
 * @package services\infusion
 */
class QueueDrugService extends Service
{
    /**
     * 排队药品列表
     * @param int|array $queueIds
     * @return array
     */
    public function getQueueDrugMapList($queueIds): array
    {
        $data = InfusionQueueDrug::find()->alias('iqd')
            ->select([
                'iqd.id', 'iqd.queue_id', 'iqd.patient_user_id', 'iqd.use_num', 'iqd.drug_config_id', 'iqd.drug_surplus_id',
                'dc.drug_id', 'dc.drug_type', 'dc.drug_volume', 'dc.water_type', 'dc.water_volume',
                'd.drug_name', 'd.drug_unit',
            ])
            ->innerJoin(DrugConfig::tableName().' dc', 'dc.id = iqd.drug_config_id')
            ->leftJoin(Drug::tableName().' d', 'd.id = dc.drug_id')
            ->where([
                'iqd.queue_id' => $queueIds
            ])
            ->orderBy([
                'iqd.id' => SORT_ASC,
            ])
            ->asArray()
            ->all();

        $map = [];
        foreach ($data as $row) {
            $drugContent = DrugService::getDrugContent((int)$row['drug_id'], $row['drug_name'], $row['drug_unit'], $row['drug_type'], $row['drug_volume'], $row['water_type'], $row['water_volume']);
            $drugPrintContent = DrugService::getDrugPrintContent((int)$row['drug_id'], $row['drug_name'], $row['drug_unit'], $row['drug_type'], $row['drug_volume'], $row['water_type'], $row['water_volume']);

            // 获取最后一次药品备注
            $drugRemark = TreatmentService::getLastDrugRemark($row['drug_config_id'], $row['patient_user_id']);
            $item = [
                'drug_id' => $row['drug_id'],
                'drug_surplus_id' => $row['drug_surplus_id'],
                'drug_config_id' => $row['drug_config_id'],
                'drug_content' => $drugContent,
                'drug_print_content' => $drugPrintContent,
                'drug_name' => $row['drug_name'],
                'drug_unit' => $row['drug_unit'],
                'drug_type' => $row['drug_type'],
                'drug_volume' => round($row['drug_volume'], 2),
                'water_type' => DrugConfig::$waterPrintTypes[$row['water_type']] ?? '',
                'water_volume' => $row['water_volume'],
                'drug_remark' => $drugRemark,
            ];

            $map[$row['queue_id']] = $map[$row['queue_id']] ?? [];
            $map[$row['queue_id']][] = $item;
        }

        return $map;
    }

    /**
     * @param int $queueId
     * @return InfusionQueueDrug[]
     */
    public static function getQueueDrugList(int $queueId): array
    {
        return InfusionQueueDrug::findAll(['queue_id' => $queueId]);
    }
}